#coding=utf-8
from uliweb import expose

#可以省略直接引用
from uliweb import request, error, redirect
import simplejson
from sqlalchemy.sql import and_, or_, not_

import sys
reload(sys)
sys.setdefaultencoding('utf8')

def __begin__():
    """
    用户验证
    """
    from uliweb import functions
    return functions.require_login()

@expose('/idcpost')
class PostData(object):

    def __init__(self):
        from uliweb.orm import get_model
        self.networkbusinessmodel = get_model('networkbusiness')
        self.computerroommodel = get_model('computerroom')
        self.rackspacemodel = get_model('rackspace')
        self.ippoolmodel = get_model('ippool')
        self.ipaddrmodel = get_model('ipaddress')

    def networkbusiness(self):
        """
        返回给jquery easyui的datagride

        所有运营商的数据
        """
        pageIndex= int(request.POST.get('page',0))
        pageSize = int(request.POST.get('rows',20))
        #排序使用
        order_by_type = request.POST.get('order','asc')
        order_by_sort = request.POST.get('sort','id')
        order_by = order_by_sort + ' ' + order_by_type 
        
        if pageIndex == 0:
            pageIndex = 1
            content = 0
        else:
            content = pageSize * (pageIndex - 1)

        data = {}
        data['total'] = self.networkbusinessmodel.all().count()
        data['rows'] = []


        data_info = {'data':self.networkbusinessmodel.all().order_by(order_by).limit(pageSize).offset(content)}

        for i in data_info['data']:

            data['rows'].append({"id":i.id,
                                 "networkbusiness_name":i.networkbusiness_name
                                 })
        #返回json串
        return json(data)


    def computerroom(self):
        """
        返回给jquery easyui的datagride

        所有机房的数据
        """
        pageIndex= int(request.POST.get('page',0))
        pageSize = int(request.POST.get('rows',20))
        #排序使用
        order_by_type = request.POST.get('order','asc')
        order_by_sort = request.POST.get('sort','id')
        order_by = order_by_sort + ' ' + order_by_type 
                
        if pageIndex == 0:
            pageIndex = 1
            content = 0
        else:
            content = pageSize * (pageIndex - 1)

        data = {}
        data['rows'] = []


        data['total'] = self.computerroommodel.all().count()
        data_info = {'data':self.computerroommodel.all().order_by(order_by).limit(pageSize).offset(content)}

        for i in data_info['data']:

            #拼接出完整的机房地址
            address = i.province_id.province_name + ' ' + i.city_id.city_name + ' ' + \
                i.area_id.area_name + ' ' + i.cr_address

            data['rows'].append({"id":i.id,
                                 "networkbusiness_id":i.networkbusiness_id.networkbusiness_name,
                                 "cr_name":i.cr_name,
                                 "cr_level":i.cr_level,
                                 "cr_phone":i.cr_phone,
                                 "cr_tech_linkname":i.cr_tech_linkname,
                                 "cr_tech_phone":i.cr_tech_phone,
                                 "cr_chat_tools":i.cr_chat_tools,
                                 "cr_sales":i.cr_sales,
                                 "cr_sales_phone":i.cr_sales_phone,
                                 "cr_sales_mobile":i.cr_sales_mobile,
                                 "cr_sales_email":i.cr_sales_email,
                                 "address":address,
                                 "comment":i.comment
                                 })
        #返回json串
        return json(data)   

    def rackspace(self):
        """
        返回给jquery easyui的datagride

        所有机柜的数据
        """
        pageIndex= int(request.POST.get('page',0))
        pageSize = int(request.POST.get('rows',20))
        
        #排序使用
        order_by_type = request.POST.get('order','asc')
        order_by_sort = request.POST.get('sort','id')
        order_by = order_by_sort + ' ' + order_by_type 
        
        #搜索
        cr_name = request.POST.get('cr_name','')
        rackspace_name = request.POST.get('rackspace_name','')
        
        if pageIndex == 0:
            pageIndex = 1
            content = 0
        else:
            content = pageSize * (pageIndex - 1)

        data = {}
        data['rows'] = []

        #functions.set_echo(True)
        if cr_name != "" or rackspace_name != "":
            
            #自己
            #cr_data = list(self.computerroommodel.filter(self.computerroommodel.c.cr_name.like('%%' + cr_name + '%%')))
            
            #cr_id = []
            #for i in cr_data:
                #cr_id.append(i.id)
            
            #data['total'] = self.rackspacemodel.filter(self.rackspacemodel.c.computerroom_id.in_(cr_id)).filter(self.rackspacemodel.c.rackspace_name.like('%%' + rackspace_name + '%%')).count()
            #data_info = {'data':self.rackspacemodel.filter(self.rackspacemodel.c.computerroom_id.in_(cr_id)).filter(self.rackspacemodel.c.rackspace_name.like('%%' + rackspace_name + '%%')).limit(pageSize).offset(content)}
            
            #标准
            data['total'] = self.rackspacemodel.filter(self.rackspacemodel.c.computerroom_id == self.computerroommodel.c.id).filter(self.computerroommodel.c.cr_name.like('%%' + cr_name + '%%')).filter(self.rackspacemodel.c.rackspace_name.like('%%' + rackspace_name + '%%')).count()
            data_info = {'data':self.rackspacemodel.filter(self.rackspacemodel.c.computerroom_id == self.computerroommodel.c.id).filter(self.computerroommodel.c.cr_name.like('%%' + cr_name + '%%')).filter(self.rackspacemodel.c.rackspace_name.like('%%' + rackspace_name + '%%')).limit(pageSize).offset(content)}
            
        else:        
            data['total'] = self.rackspacemodel.all().count()
            data_info = {'data':self.rackspacemodel.all().order_by(order_by).limit(pageSize).offset(content)}

        for i in data_info['data']:

            data['rows'].append({"id":i.id,
                                 "rackspace_name":i.rackspace_name,
                                 "computerroom_id":i.computerroom_id.cr_name,
                                 "comment":i.comment
                                 })
        #返回json串
        return json(data)    

    def ippool(self):
        """
        返回给jquery easyui的datagride

        所有ip池的数据
        """
        pageIndex= int(request.POST.get('page',0))
        pageSize = int(request.POST.get('rows',20))
        #排序使用
        order_by_type = request.POST.get('order','asc')
        order_by_sort = request.POST.get('sort','id')
        order_by = order_by_sort + ' ' + order_by_type 
        
        _id = request.POST.get('cr_name','')
        ippool_prefix = request.POST.get('ippool_prefix','')
        
        if pageIndex == 0:
            pageIndex = 1
            content = 0
        else:
            content = pageSize * (pageIndex - 1)

        data = {}
        
        data['rows'] = []


        if _id !='' and ippool_prefix != '':
            data['total'] = self.ippoolmodel.filter(self.ippoolmodel.c.computerroom_id == int(_id)).filter(self.ippoolmodel.c.ippool_prefix.like('%%' + ippool_prefix + '%%')).count()
            data_info = {'data':self.ippoolmodel.filter(self.ippoolmodel.c.computerroom_id == int(_id)).filter(self.ippoolmodel.c.ippool_prefix.like('%%' + ippool_prefix + '%%')).limit(pageSize).offset(content)}
        elif _id =='' and ippool_prefix != '':
            data['total'] = self.ippoolmodel.filter(self.ippoolmodel.c.ippool_prefix.like('%%' + ippool_prefix + '%%')).count()
            data_info = {'data':self.ippoolmodel.filter(self.ippoolmodel.c.ippool_prefix.like('%%' + ippool_prefix + '%%')).limit(pageSize).offset(content)}
        elif _id != '' and ippool_prefix == '':
            data['total'] = self.ippoolmodel.filter(self.ippoolmodel.c.computerroom_id == int(_id)).count()
            data_info = {'data':self.ippoolmodel.filter(self.ippoolmodel.c.computerroom_id == int(_id)).offset(content)}            
        else:
            data['total'] = self.ippoolmodel.all().count()
            data_info = {'data':self.ippoolmodel.all().order_by(order_by).limit(pageSize).offset(content)}

        for i in data_info['data']:

            if i.computerroom_id == None:
                computerroom_id = ""
            else:
                computerroom_id = i.computerroom_id.cr_name
            #得到已经使用的IP
            used = i.pool.filter(self.ipaddrmodel.c.ip_status == 1).count()

            data['rows'].append({"id":i.id,
                                 "ippool_prefix":i.ippool_prefix,
                                 "ippool_netmask":i.ippool_netmask,
                                 "ippool_len":i.ippool_len,
                                 "ippool_gateway":i.ippool_gateway,
                                 "computerroom_id":computerroom_id,
                                 "ip_not_used":i.ippool_len - used,
                                 "comment":i.comment
                                 })
        #返回json串
        return json(data) 

####################################################################################################    

    def networkbusinessinfo(self):
        """
        获取运营商名称，提供给combobox
        """

        data = []
        data_info = {'data':self.networkbusinessmodel.all().order_by(self.networkbusinessmodel.c.id)}

        for i in data_info['data']:

            data.append({"id":i.id,
                         "networkbusiness_name":i.networkbusiness_name
                         })

        #返回json串
        return json(data)
    

    def computerroominfo(self):
        """
        获取机房名称，提供给combobox
        """

        data = []
        data_info = {'data':self.computerroommodel.all().order_by(self.computerroommodel.c.id)}

        for i in data_info['data']:

            data.append({"id":i.id,
                         "cr_name":i.cr_name
                         })

        #返回json串
        return json(data)
    
    def computerroomsearch(self):
        """
        获取机房名称，提供给combobox的自动补全使用
        """
        
        #functions.set_echo(True)

        search = request.POST.get('q','')
        
        data = []
        data_info = {'data':self.computerroommodel.filter(self.computerroommodel.c.cr_name.like('%%' + search + '%%')).order_by(self.computerroommodel.c.id)}

        for i in data_info['data']:

            data.append({"id":i.id,
                         "cr_name":i.cr_name
                         })

        #返回json串
        return json(data)

    def computerroomsearch2(self):
        """
        获取机房名称，提供给combobox的自动补全使用
        """
        
        #functions.set_echo(True)

        search = request.GET.get('keyword','')
        
        data = []
        data_info = {'data':self.computerroommodel.filter(self.computerroommodel.c.cr_name.like('%%' + search + '%%')).order_by(self.computerroommodel.c.id)}

        for i in data_info['data']:

            data.append({"id":i.id,
                         "value":i.cr_name,
                         "label":i.cr_name
                         })

        #返回json串
        return json(data)    
    
    
    def rackspaceinfo(self):
        """
        获取机柜信息，提供给combobox
        """
        
        _id = request.GET.get("id")

        data = []
        
        data_info = {'data':self.rackspacemodel.filter(self.rackspacemodel.c.computerroom_id == _id)}
        for i in data_info['data']:

            data.append({"id":i.id,
                         "rackspace_name":i.rackspace_name
                         })

        #返回json串
        return json(data)
    
    def ippoolinfo(self):
        """
        获取ip池信息，提供给combobox
        参数:
             id:机房ID
        """

        _id = request.GET.get("id")
        data = []

        data_info = {'data':self.ippoolmodel.filter(self.ippoolmodel.c.computerroom_id == _id)}

        for i in data_info['data']:

            data.append({"id":i.id,
                         "ippool_prefix":i.ippool_prefix
                         })

        #返回json串
        return json(data)
    
    def computerroomtree(self):
        """
        异步加载机房菜单
        """
        pid = request.GET.get("pid")
        treedata = []
        if pid == "0":
                treedata.append({"id":"99999999",
                                 "text":"机房树",
                                 "state":"closed",
                                 "checked":False
                                 })
        
        else:
            data = self.computerroommodel.all().order_by(self.computerroommodel.c.id)

            for i in data:

                treedata.append({"id":i.id,
                                "text":i.cr_name,
                                "state":"open",
                                "checked":False
                                })

        return json(treedata)    
    
    def computerroomtreegraph(self):
        """
        机房树,用于显示机柜和设备图
        """
        _id = request.POST.get("id")
        treedata = []
        if _id == None:
            treedata.append({"id":"99999999",
                             "text":"机房树",
                             "state":"closed",
                             "checked":False,
                             "attributes":{"url":""}
                             })
    
        else:
            data = self.computerroommodel.all().order_by(self.computerroommodel.c.id)

            for i in data:

                treedata.append({"id":i.id,
                                "text":i.cr_name,
                                "state":"open",
                                "checked":False,
                                "attributes":{"url":"/devices/devicesrackspace?id=" + str(i.id)}
                                })

        return json(treedata)         